package com.mtzqc.common.manager

import com.mtzqc.common.kt.loadService
import com.mtzqc.common.service.KvService

object KvManager {
    val service: KvService by lazy {
        loadService()
    }

    inline fun <reified T> get(key: String, defaultValue: T): T {
        return get(key, T::class.java, defaultValue) ?: defaultValue
    }

    inline fun <reified T> get(key: String): T? {
        return get(key, T::class.java, null)
    }


    fun <T> get(key: String?, clazz: Class<T>, defaultValue: T? = null): T? {
        if (key.isNullOrBlank()) {
            return defaultValue
        }
        return service.get(key, clazz) ?: defaultValue
    }

    inline fun <reified T> getArray(key: String): List<T>? {
        return getArray(key, T::class.java)
    }

    fun <T> getArray(key: String?, clazz: Class<T>): List<T>? {
        if (key.isNullOrBlank()) {
            return null
        }
        return get<String>(key)?.let {
            JsonManager.fromJsonArray(it, clazz)
        }
    }

    fun put(key: String?, value: Any?): Boolean {
        if (key.isNullOrBlank() || null == value) {
            return false
        }
        return service.put(key, value)
    }

    fun containsKey(key: String?): Boolean {
        if (key.isNullOrBlank()) {
            return false
        }
        return service.containsKey(key)
    }

    fun remove(key: String?) {
        if (!key.isNullOrBlank()) {
            service.remove(key)
        }
    }
}